<?php
namespace app\api\controller;
use app\api\model\Device as DeviceModel;
use app\api\model\User as UserModel;
use app\api\controller\Map;
use app\api\controller\Devicetool;
use think\Db;
use think\Request;


class Device extends Base{

    public function _initialize()
    {
        parent::_initialize();
        Vendor('iot.demo.Device#Util');
    }



    /**
     * Notes: 添加设备
     * Create Date: 2018/10/2
     * Create by :lijie
     */
    public function addDevice(Request $request){
        // 验证
        $param = $request->post();
        $resVali = $this->validate($param,"DeviceValidate.addDevice");
        if($resVali !== true){
            return apiResponse(201,$resVali,'');
        }

        // 判断设备是否已经添加过
        $wheredevice = [
            'device_id' => input('post.device_id'),
            'status' => ['neq',9]
        ];
        $obd = Db::name('device')->where($wheredevice)->field("id")->find();
        if(!empty($obd))    return apiResponse(201,'该编号的设备已经存在','');

        // $t = new \Util();
        $tool = new Devicetool();
        $productKey = input('post.productKey');
        if (empty($productKey)) {
            $productKey = 'a1plNZn0KLj';
        }
        // $response = $tool->registDevice(input('post.device_id'),$productKey);
        // if ( !$response -> Success ) {
        //     $param['device_iot_id'] = $response -> deviceId;
        //     $param['device_iot_secret'] = $response -> deviceSecret;
        //     return apiResponse("201","设备注册失败！".$response -> ErrorMessage);
        // }
        
        // file_put_contents('response.txt',json_encode($response));
        //  创建时间
        $ctime = time();
        $param['update_time'] = $ctime;
        $param['create_time'] = $ctime;
        $param['device_qrcode_id'] = time().mt_rand(1000,9999);
        $param['product_iot_id'] = $productKey;
        
        // $qrcode_Url = "https://open.weixin.qq.com/sns/getexpappinfo?appid=wx7c738b894c90dcc8&path=pages/firstPage/first.html&device_qrcode_id=".$param['device_qrcode_id']."#wechat-redirect";
        $path_pic = $this -> getCodePic( $param['device_qrcode_id'] );
        // $this->getPng($qrcode_Url,$path);       
        $param['qrcodeurl'] = $path_pic;
        $res = Db::name('device')->insert($param);
        if($res){
            return apiResponse(200,'添加成功','');
        }else {
            return apiResponse(201,'添加失败','');
        }
    }

    
     /*
      * Notes: 设备列表
      * Create Date: 2018/10/9
      * Create Time: 上午9:35
      * Create by :张福来
      * pagenum : 查询页数
      * listNum : 条数
      * id : 设备编号
      * status : 设备状态 1不可用 2可用
      * start_time : 开始时间
      * end_time : 结束时间
      */
    public function getDevice(Request $request){
        $device = new DeviceModel();
        $postData = $request->post();
        $check = $this->validate($postData,"DeviceValidate.deviceList");
        if($check !== true){
            return apiResponse(201,$check,"");
        }
        $pageNum = empty($postData["pagenum"]) ? 1 : $postData["pagenum"];
        if(empty($postData["listNum"])){
            $listNum = 10;
        }else{
            $listNum= $postData["listNum"];
        }
        if(!empty($postData["id"])){
            $w["id"] = $postData["id"];
        }
        if(!empty($postData["c_id"])){
            $w["c_id"] = $postData["c_id"];
        }
        if(empty($postData["status"])){
            $w["status"] = array('NEQ',9);
        }else{
            $w["status"] = $postData["status"];
        }
        if(!empty($postData["start_time"]) && !empty($postData["end_time"])){
            $start_time = input('post.start_time'). " 00:00:00";
            $end_time = input('post.end_time'). " 23:59:59";
            $w['create_time'] = array(array('EGT',$start_time),array('ELT',$end_time),'and');
        }
        
        if (empty($postData["lat"]) || empty($postData["lon"])) {
            $result = $device -> deviceList($pageNum,$listNum,$w);
        }else{
            $lat = $postData["lat"];
            $lon = $postData["lon"];
            $result = $device -> deviceListByLatLon($pageNum,$listNum,$w,$lat,$lon);
        }
        return apiResponse(200,'查询成功',$result);

    }

    /**
     * Notes:  编辑设备信息
     * Create Date: 2018/10/3
     * Create by :lijie
     */
    public function editDevice(Request $request)
    {   
        $device = new DeviceModel();
        $param = $request->post();
        $vali  = $this->validate($param,"DeviceValidate.editCoupon");
        if($vali !== true){
            return apiResponse(201,$vali,'');
        }
        $where['id'] = $param['id'];
        $param['update_time'] = time();
        $res = $device->updateDevice($param,$where);
        if($res){
            return apiResponse(200,'编辑成功',$res);
        }else {
            return apiResponse(201,"编辑失败",$res);
        }
    }


    /**
     * Notes:  编辑设备状态
     * Create Date: 2018/10/3
     * Create by :lijie
     */
    public function updDevice(Request $request)
    {   
        $device = new DeviceModel();
        $param = $request->post();
        
        // $vali  = $this->validate($param,"DeviceValidate.editCoupon");
        // if($vali !== true){
        //     return apiResponse(201,$vali,'');
        // }
        $where['device_id'] = $param['device_id'];
        $param['update_time'] = time();
        $res = $device->updateDevice($param,$where);
        if($res){
            return apiResponse(200,'编辑成功',$res);
        }else {
            return apiResponse(201,"编辑失败",$res);
        }
    }

    /**
     * 更新小程序码，小程序和设备码二合一
     * @author topqiang
     * @DateTime 2019-01-27T09:49:07+0800
     * @param    Request                  $request [description]
     * @return   [type]                            [description]
     */
    public function updQrcode(Request $request)
    {   
        $device = new DeviceModel();
        $param = $request->post();
        // $vali  = $this->validate($param,"DeviceValidate.editCoupon");
        // if($vali !== true){
        //     return apiResponse(201,$vali,'');
        // }
        $where['device_id'] = $param['device_id'];
        $param['update_time'] = time();
        $path_pic = $this -> getCodePic( $param['device_qrcode_id'] );
        if (empty($path_pic)) {
            return apiResponse(201,"小程序码更新失败！");
        }else{
            $param['qrcodeurl'] = $path_pic;
            $res = $device->updateDevice($param,$where);
            if($res){
                return apiResponse(200,'小程序码更新成功！',$res);
            }else {
                return apiResponse(201,"数据更新失败！",$res);
            }
        }
        
    }

    /**
     * 操作设备
     * @author topqiang
     * @DateTime 2019-01-26T20:32:28+0800
     * @param    Request                  $request [description]
     * @return   [type]                            [description]
     */
    public function playDevice(Request $request)
    {
        $param = $request->post();
        $vali  = $this->validate($param,"DeviceValidate.playDevice");
        if($vali !== true){
            return apiResponse(201,$vali,'');
        }
        if ( $param['operate'] == 'start' ) {
            $params['device_status'] = 2;
            $whereupdorder['status']= 2;
            $dataorder['status']= 3;
            if (!empty($param['o_id'])) {
                $updorder['id']= $param['o_id'];
                $updorder['status']= ['in',[2,3]];
                $orderitem = Db::name('order')->where($updorder)->find();
                if (empty($orderitem)) {
                    return apiResponse("201","订单状态已发生改变！");
                }
            }
            $params['last_use_time'] = time();
        }else{
            $params['device_status'] = 1;
            $whereupdorder['status']= 3;
            $dataorder['status']= 4;
        }
        $tool = new Devicetool();
        $res = $tool -> test($param['product_iot_id'],$param['device_id'],$param['operate']);
        if ($res['code'] == "200") {
            $device = new DeviceModel();
            $where['device_id'] = $param['device_id'];
            if (!empty($param['o_id'])) {
                $whereupdorder['id']= $param['o_id'];
                $dataorder['utime']= time();
                Db::name('order')->where($whereupdorder)->update($dataorder);
            }
            //设备启动成功，修改设备状态
            $res1 = $device->updateDevice($params,$where);
        }
        return $res;
    }

    // 打开卷帘门
    public function opendoor(Request $request){
        $param = $request->post();
        $vali = $this->validate($param,"DeviceValidate.playDevice");
        if($vali !== true){
            return apiResponse(201,$vali,'');
        }
        $messageArray = ["getType" => "door","time" => time()*1000,"data" => []];
        $tool = new Devicetool();
        return $tool -> test($param['product_iot_id'],$param['device_id'],$param['operate'],$messageArray);
    }

    /**
     * 获取消息队列消息
     * @author topqiang
     * @DateTime 2019-01-26T20:32:07+0800
     * @param    Request                  $request [description]
     * @return   [type]                            [description]
     */
    public function mnstest(Request $request)
    {
        $param = $request->post();
        $vali  = $this->validate($param,"DeviceValidate.mnstest");
        if($vali !== true){
            return apiResponse(201,$vali,'');
        }
        $tool = new Devicetool();
        $res = $tool -> mnstest($param['msgid']);
        return $res;
    }

    /**
     * 发送获取设备状态的指令
     * @author topqiang
     * @DateTime 2019-01-26T20:32:41+0800
     * @param    Request                  $request [description]
     * @return   [type]                            [description]
     */
    public function putStatus(Request $request)
    {
        $param = $request->post();
        $vali  = $this->validate($param,"DeviceValidate.putStatus");
        if($vali !== true){
            return apiResponse(201,$vali,'');
        }
        $tool = new Devicetool();
        $res = $tool -> putStatus($param['device_id'],$param['product_iot_id']);
        return $res;
    }

    /**
     * Notes:  设备详情
     * Create Date: 2018/10/3
     * Create by :topqiang
     */
    public function deviceInfo( Request $request )
    {   
        $device = new DeviceModel();
        $param = $request->post();
        $vali  = $this->validate($param,"DeviceValidate.deviceInfo");
        if($vali !== true){
            return apiResponse(201,$vali,'');
        }
        $res = $device -> deviceInfo($param);
        if($res){
            return apiResponse(200,'获取成功',$res);
        }else {
            return apiResponse(201,"获取失败",$res);
        }
    }


    /**
     * 通过识别码识别设备
     * @author topqiang
     * @DateTime 2019-01-26T20:33:01+0800
     * @param    Request                  $request [description]
     * @return   [type]                            [description]
     */
    public function qrcodeDevice(Request $request)
    {
        $device = new DeviceModel();
        $param = $request->post();
        $res = $device -> deviceInfo($param);
        if($res){
            return apiResponse(200,'获取成功',$res);
        }else {
            return apiResponse(201,"获取失败",$res);
        }
    }

    /**
     * [delDevice description]
     * @author topqiang
     * @DateTime 2018-09-02T12:02:53+0800
     * @return   [type]                   [description]
     */
    public function delDevice()
    {   
        $device = new DeviceModel();
        $id = input('post.id');
        if(empty($id)){
            return apiResponse(201,"id不能为空",'');
        }
        //
        $res = $device -> delDevice($id);
        if($res){
            return apiResponse(200,'删除成功',$res);
        }else {
            return apiResponse(201,"删除失败",$res);
        }
    }

    /**
     * 生成统一的设备和小程序码
     * @author topqiang
     * @DateTime 2019-01-26T20:37:15+0800
     * @param    [type]                   $qrcode_id [description]
     * @param    [type]                   $filepath  [description]
     * @return   [type]                              [description]
     */
    public function getCodePic($qrcode_id){
        header('content-type:image/jpg');
        $accessToken = getAccessToken();
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$accessToken";
        $data = array(
            'scene' => "200,".$qrcode_id,
            'width' => 430,
            'page' => 'pages/firstPage/first'
            );
        $res = get_curl_request($url,"POST",json_encode($data));
        if (!empty($res['errcode'])) {
            return false;
        }else{
            $png_name  = date("YmdHis",time());
        
            // 判断二维码目录是否存在，不存在则创建目录
            $saveRoot = ROOT_PATH."public/code/".$png_name.'/';
            if(!is_dir($saveRoot)){
                mkdir($saveRoot,0777,true);
            }

            //  二维码图片路径
            $path_pic = "code/".$png_name.'/'.$png_name.".png";               //  数据库二维码图片保存的路径
            $path = $saveRoot.$png_name.".png";                               //  图片目录路径
            file_put_contents($path,$res);
            return $path_pic;
        }
    }


    public function getCapture( Request $request ){
        // $url = "https://open.ys7.com/api/lapp/device/capture";
        // $url = "https://open.ys7.com/api/lapp/device/support/ezviz";
        // $url = "https://open.ys7.com/api/lapp/live/video/list";
        $url = "https://open.ys7.com/api/lapp/live/address/limited";
        $data = array(
            'accessToken' => getTokenForYS(),
            // 'appKey' => 'caf3065c691843c58f79a562e52ccf01',
            // 'model' => 'CS-C3WN-1B2WFR',
            // 'version'=>'V1.0',
            'channelNo' => 1
            );
        if (empty(input("post.deviceSerial"))) {
            $data['deviceSerial'] = 'c39731130';
        }else{
            $data['deviceSerial'] = input("post.deviceSerial");
        }
        $res = json_decode(curl_request( $url , $data ),true);

        if ( $res['code'] = 200 && !empty($res['data'])) {
            
            if (empty( $res['data']['rtmp'] )) {
               return apiResponse("201","未获取到rtmp流！");
            }else{
                $rtmp = $res['data']['rtmp'];
                $filename = $data['deviceSerial'].time().".png";
                $exec1 = "avconv -i $rtmp -f image2 -ss 0 -vframes 1 -s 400*250 /home/wwwroot/mini.kuchengxiche.cn/public/capture/$filename";
                //ffmpeg -i $rtmp -f image2 -ss 0 -vframes 1 -s 400*250 /home/wwwroot/ai.kanziqiang.top/public/capture/$filename
                exec($exec1,$info,$status);
                // file_put_contents('1.txt',$exec1);
                // file_put_contents('2.txt',json_encode($info));
                // file_put_contents('3.txt',$status);
                if ($status==0) {
                    return apiResponse("200","获取成功！","capture/$filename");
                }else{
                    return apiResponse("201","获取截图失败！");
                }
            }
        }else{
            return apiResponse("201","获取直播流失败！",$res);
        }
    }

    public function getToken(){
        dump(getTokenForYS());
    }
}


